package com.campus.commons.utils;


import org.springframework.format.datetime.DateFormatter;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.annotation.WebServlet;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@ControllerAdvice(basePackages = "com.campus.web.controller")
@ResponseBody
public class AllErrorHander {


    @InitBinder
    public void WebBinder(WebDataBinder dataBinder) {
        dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }


    @ExceptionHandler
    public Result errors(ConstraintViolationException e) {
        Map<String, String> map = new Hashtable<>();
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation c : constraintViolations) {
            String msg=c.getPropertyPath().toString();
            msg = msg.substring(msg.lastIndexOf(".")+1);
            map.put(msg, c.getMessage());
        }
        return Result.error(Error.PARAMS_E3R, map);
    }

    @ExceptionHandler
    public Result bindException(BindException e) { //这个会在Controller中抛出
        return Result.error(Error.PARAMS_E3R, e.getBindingResult().getAllErrors().stream().map(s -> s.getDefaultMessage()).collect(Collectors.toList()));
    }
    @ExceptionHandler
    public ModelAndView exception(Exception e, ModelMap modelMap) {
//        DebugError.openDebug();
        DebugError.show(e);
        modelMap.addAttribute("data",Result.error(Error.System_E1R, e));
        return new ModelAndView("error/408",modelMap);
    }
}

